<!-- src/views/HomeView.vue -->
<template>
  <div class="home">
    <!-- 欢迎横幅 -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">欢迎来到乒乓社区！</h1>
        <p class="hero-subtitle">这里是乒乓球爱好者的聚集地，分享技术、交流心得、结识球友。</p>
        <el-button type="primary" size="large" @click="goToCategories">立即浏览所有板块</el-button>
      </div>
      <div class="hero-image">
        <!-- 可以替换为一张高质量的乒乓球运动图片或抽象图形 -->
        <img src="https://www.kepuchina.cn/more/202108/W020210802524008734865.jpg" alt="乒乓球运动" />
      </div>
    </div>

    <!-- 特色功能/公告区域 -->
    <div class="features-grid">
      <div class="feature-card">
        <div class="feature-icon">
          <i class="el-icon el-icon-s-custom"></i>
        </div>
        <h3>技术讨论</h3>
        <p>深入探讨发球、接发球、步法、战术等技术细节，提升你的乒乓球水平。</p>
      </div>
      <div class="feature-card">
        <div class="feature-icon">
          <i class="el-icon el-icon-s-claim"></i>
        </div>
        <h3>器材评测</h3>
        <p>分享你使用过的底板、胶皮、球拍的体验，帮助大家选择最适合自己的装备。</p>
      </div>
      <div class="feature-card">
        <div class="feature-icon">
          <i class="el-icon el-icon-s-check"></i>
        </div>
        <h3>赛事资讯</h3>
        <p>第一时间获取国际乒联 (ITTF)、中国乒协等官方赛事信息和赛况分析。</p>
      </div>
    </div>

    <!-- 热门帖子列表 -->
   <!-- 热门帖子列表 -->
    <div class="section-title">
      <h2>热门帖子</h2>
      <el-link type="primary" @click="goToPosts">查看更多</el-link>
    </div>
    <!-- *** 修改点 1: 添加加载和错误状态显示 *** -->
    <div v-loading="postsLoading" element-loading-text="拼命加载中">
      <el-alert
        v-if="postsErrorMessage"
        :title="postsErrorMessage"
        type="error"
        show-icon
        closable
        style="margin-bottom: 20px;"
      />
      <div v-if="hotPosts.length === 0 && !postsLoading" class="no-posts">
        <p>暂无热门帖子。</p>
      </div>
      <!-- *** --- *** -->
      <!-- *** 修改点 2: 条件渲染列表，并使用正确的数据源 *** -->
      <div class="posts-list" v-else>
        <el-table :data="hotPosts" style="width: 100%" stripe>
          <el-table-column prop="title" label="标题" min-width="300">
            <template #default="scope">
              <el-link @click="goToPost(scope.row.id)" type="primary">{{ scope.row.title }}</el-link>
              <el-tag v-if="scope.row.isTop" type="danger" size="small" effect="dark" style="margin-left: 8px;">置顶</el-tag>
              <el-tag v-if="scope.row.isEssence" type="warning" size="small" effect="light" style="margin-left: 4px;">精华</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="authorName" label="作者" width="120" />
          <el-table-column prop="categoryName" label="板块" width="120" />
          <el-table-column prop="viewCount" label="浏览" width="80" />
          <el-table-column prop="replyCount" label="回复" width="80" />
          <el-table-column prop="likeCount" label="点赞" width="80" />
          <el-table-column prop="createdAt" label="发布时间" width="180">
             <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>



    <!-- 板块推荐 -->
    <div class="section-title">
      <h2>推荐板块</h2>
      <el-link type="primary" @click="goToCategories">查看全部板块</el-link>
    </div>
    <div class="categories-grid">
      <el-card v-for="category in recommendedCategories" :key="category.id" class="category-card" shadow="hover">
        <div class="category-header">
          <img :src="category.iconUrl || 'https://via.placeholder.com/40x40?text=Icon'" alt="板块图标" class="category-icon" />
          <div class="category-info">
            <h3>{{ category.name }}</h3>
            <p>{{ category.description }}</p>
          </div>
        </div>
        <div class="category-stats">
          <span>帖子: {{ category.postCount }}</span>
          <span>今日: {{ category.todayPostCount }}</span>
        </div>
        <el-button type="text" @click="goToCategory(category.id)">进入板块</el-button>
      </el-card>
    </div>

    <!-- 社区动态/公告 -->
     <!-- 社区动态/公告 -->
    <div class="section-title">
      <h2>社区公告</h2>
      <!-- 可以添加“查看更多”链接 -->
    </div>
    <div class="announcements">
      <!-- *** 修改点 1: 添加加载和错误状态显示 *** -->
      <div v-loading="announcementsLoading" element-loading-text="拼命加载中">
        <el-alert
          v-if="announcementsErrorMessage"
          :title="announcementsErrorMessage"
          type="error"
          show-icon
          closable
          style="margin-bottom: 20px;"
        />
        <div v-if="announcements.length === 0 && !announcementsLoading" class="no-announcements">
          <p>暂无社区公告。</p>
        </div>
        <!-- *** --- *** -->
        <!-- *** 修改点 2: 使用 el-timeline 展示公告列表 *** -->
        <el-timeline v-else>
          <el-timeline-item
            v-for="(announcement, index) in announcements"
            :key="announcement.id"
            :timestamp="formatDate(announcement.createdAt)"
            :color="announcement.type === 2 ? '#f56c6c' : '#409eff'"
            :size="announcement.size || 'normal'"
            placement="top"
          >
            <div class="announcement-content">
              <h3>{{ announcement.title }}</h3>
              <p>{{ truncateContent(announcement.content, 100) }}</p> <!-- 截断内容 -->
              <el-button type="text" size="small" @click="readMore(announcement.id)">阅读详情</el-button>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <!-- *** --- *** -->
    </div>

    <!-- 底部页脚 (已包含在 MainLayout 中) -->
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { getCategories } from '@/services/categoryService';
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getPopularPosts } from '@/services/postService';
// --- 修改点 3: 导入获取热门帖子的 API 服务 ---
import { getHotPosts } from '@/services/postService';
import { getActiveAnnouncements } from '@/services/apiService';

const router = useRouter();

const loading = ref(false);
const errorMessage = ref('');
const categories = ref([]);

// --- 修改点 3: 为热门帖子模块添加状态管理 ---
const postsLoading = ref(false); // 热门帖子加载状态
const postsErrorMessage = ref(''); // 热门帖子错误信息
const hotPosts = ref([]); // 存储热门帖子列表



const recommendedCategories = ref([
  {
    id: 1,
    name: "技术讨论区",
    description: "讨论乒乓球技术和器材",
    iconUrl: "https://img95.699pic.com/photo/60038/9554.jpg_wh860.jpg",
    postCount: "",
    todayPostCount: ""
  },
  {
    id: 2,
    name: "器材评测",
    description: "分享底板、胶皮、球拍的使用体验",
    iconUrl: "https://p1.ssl.qhmsg.com/t015ce75f7665622ba3.jpg",
    postCount: "",
    todayPostCount: ""
  },
  {
    id: 3,
    name: "赛事资讯",
    description: "最新比赛结果、新闻和分析。让每一个乒油们都能在第一时间获取最新资讯。",
    iconUrl: "https://ts1.tc.mm.bing.net/th/id/OIP-C.8yLnag4-KNHA3LlW1nY8igHaHa?r=0&rs=1&pid=ImgDetMain&o=7&rm=3",
    postCount: "",
    todayPostCount: ""
  }
]);

// --- 修改点 4: 为公告模块添加状态管理 ---
const announcementsLoading = ref(false);
const announcementsErrorMessage = ref('');
const announcements = ref([]); // 存储公告列表

// --- 方法 ---
const goToCategories = () => {
  router.push('/categories');
};

const goToPosts = () => {
  router.push('/posts');
};

const goToPost = (postId) => {
  router.push(`/posts/${postId}`);
};

const goToCategory = (categoryId) => {
  router.push(`/categories/${categoryId}`);
};

const readMore = (announcementId) => {
  // router.push(`/announcements/${announcementId}`); // 跳转到公告详情页
  // 或者使用命名路由 (需要在 router/index.js 中配置)
  router.push({ name: 'announcement-detail', params: { id: announcementId } });
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// --- 修改点 4: 获取热门帖子列表 ---
const fetchPopularPosts = async (page = 0, size = 3) => { // 默认获取第一页，5条数据
  postsLoading.value = true;
  postsErrorMessage.value = '';
  try {
    // 调用真实的 API 服务
    const response = await getPopularPosts({
      page: page,
      size: size
      // 可以添加其他参数，如按天数筛选热门 (lastNDays) 或排序方式
      // lastNDays: 7, // 获取近7天热门
      // sortBy: 'viewCount', // 或 'replyCount'
      // sortDir: 'desc'
    });
    // 假设后端返回的是分页数据 { content: [...], totalElements: ... }
    hotPosts.value = response.data.content || [];
  } catch (error) {
    console.error('Failed to fetch popular posts:', error);
    postsErrorMessage.value = error.response?.data?.message || '获取热门帖子列表失败';
    ElMessage.error(postsErrorMessage.value);
    hotPosts.value = []; // 出错时清空列表
  } finally {
    postsLoading.value = false;
  }
};
// --- 修改点 5: 获取热门帖子列表 ---
const fetchHotPosts = async (page = 0, size = 5) => { // 默认获取第一页，5条数据
  postsLoading.value = true;
  postsErrorMessage.value = '';
  try {
    // 调用真实的 API 服务
    const response = await getHotPosts({
      page: page, // 后端通常从 0 开始
      size: size,
      sortBy: 'viewCount', // 或 'replyCount'
      sortDir: 'desc' // 降序
    });
    // 假设后端返回的是分页数据 { content: [...], totalElements: ... }
    hotPosts.value = response.data.content || [];
  } catch (error) {
    console.error('Failed to fetch hot posts:', error);
    postsErrorMessage.value = error.response?.data?.message || '获取热门帖子列表失败';
    ElMessage.error(postsErrorMessage.value);
    hotPosts.value = []; // 出错时清空列表
  } finally {
    postsLoading.value = false;
  }
};

// 获取所有板块列表
const fetchCategories = async () => {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await getCategories();
    categories.value = response.data || [];
    recommendedCategories.value = response.data.slice(0, 3);
  } catch (error) {
    console.error('Failed to fetch categories:', error);
    errorMessage.value = error.response?.data?.message || '获取板块列表失败';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// --- 修改点 5: 添加截断内容的方法 ---
const truncateContent = (content, length) => {
  if (!content) return '';
  return content.length > length ? content.substring(0, length) + '...' : content;
};
// --- ---

// --- 修改点 6: 获取公告列表 ---
const fetchAnnouncements = async () => {
  announcementsLoading.value = true;
  announcementsErrorMessage.value = '';
  try {
    // 调用真实的 API 服务
    const response = await getActiveAnnouncements();
    // 假设后端返回的是公告数组 []
    announcements.value = response.data || [];
  } catch (error) {
    console.error('Failed to fetch announcements:', error);
    announcementsErrorMessage.value = error.response?.data?.message || '获取社区公告失败';
    ElMessage.error(announcementsErrorMessage.value);
    announcements.value = []; // 出错时清空列表
  } finally {
    announcementsLoading.value = false;
  }
};



// 组件挂载时获取数据
onMounted(() => {
  fetchCategories();
  fetchPopularPosts(); // 获取热门帖子列表
   fetchHotPosts();
   fetchAnnouncements();
});
</script>

<style scoped>
.home {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f5f7fa; /* 调整背景色 */
  min-height: 100vh;
}

/* 欢迎横幅 */
.hero-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 40px;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
/* --- 修改点 8: 添加无公告提示样式 --- */
.no-announcements {
  text-align: center;
  color: #999;
  font-size: 1.1em;
  margin-top: 20px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.hero-content {
  flex: 1;
  min-width: 300px;
  padding: 20px;
}

.hero-title {
  font-size: 2.5em;
  margin-bottom: 10px;
  font-weight: 700;
}

.hero-subtitle {
  font-size: 1.2em;
  margin-bottom: 20px;
  opacity: 0.9;
}

.hero-image {
  flex: 1;
  min-width: 300px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.hero-image img {
  width: 100%;
  height: auto;
  display: block;
}

/* 特色功能/公告区域 */
.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.feature-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  text-align: center;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.1);
}

.feature-icon {
  font-size: 2em;
  margin-bottom: 15px;
  color: #409eff;
}

.feature-card h3 {
  margin: 0 0 10px 0;
  font-size: 1.3em;
  color: #303133;
}

.feature-card p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

/* 分割线 */
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-title h2 {
  margin: 0;
  font-size: 1.5em;
  color: #303133;
}

/* 热门帖子列表 */
.posts-list {
  margin-bottom: 40px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 板块推荐 */
.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.category-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: transform 0.3s ease;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.1);
}

.category-header {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.category-icon {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 50%;
  margin-right: 15px;
}

.category-info h3 {
  margin: 0 0 5px 0;
  font-size: 1.2em;
  color: #303133;
}

.category-info p {
  margin: 0;
  color: #666;
  font-size: 0.9em;
}

.category-stats {
  padding: 15px 20px;
  background-color: #f5f7fa;
  font-size: 0.9em;
  color: #666;
}

.category-stats span {
  margin-right: 15px;
}

/* 社区公告 */
.announcements {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.announcement-content h3 {
  margin: 0 0 10px 0;
  font-size: 1.2em;
  color: #303133;
}

.announcement-content p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

/* 通用样式 */
.el-button--text {
  color: #409eff;
}

/* --- 修改点 8: 无帖子提示样式 --- */
.no-posts {
  text-align: center;
  color: #999;
  font-size: 1.1em;
  margin-top: 20px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

/* --- 新增: 响应式设计 ---
     *** 添加针对不同屏幕尺寸的样式 ***
*/
@media (max-width: 1200px) {
  .home {
    padding: 15px;
  }
  .hero-section {
    padding: 30px;
  }
  .hero-content {
    padding: 15px;
  }
  .hero-title {
    font-size: 2.2em;
  }
  .hero-subtitle {
    font-size: 1.1em;
  }
  .features-grid, .categories-grid, .posts-list, .announcements {
    gap: 15px;
  }
  .feature-card, .category-card {
    padding: 15px;
  }
  .category-header {
    padding: 15px;
  }
  .category-stats {
    padding: 10px 15px;
  }
}

@media (max-width: 992px) {
  .home {
    padding: 10px;
  }
  .hero-section {
    padding: 20px;
  }
  .hero-content {
    padding: 10px;
  }
  .hero-title {
    font-size: 2em;
  }
  .hero-subtitle {
    font-size: 1em;
  }
  .features-grid, .categories-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
  .feature-card, .category-card {
    padding: 12px;
  }
  .category-header {
    padding: 12px;
  }
  .category-icon {
    width: 35px;
    height: 35px;
  }
  .category-info h3 {
    font-size: 1.1em;
  }
  .category-info p {
    font-size: 0.85em;
  }
  .category-stats {
    padding: 8px 12px;
    font-size: 0.85em;
  }
}

@media (max-width: 768px) {
  .home {
    padding: 8px;
  }
  .hero-section {
    flex-direction: column;
    padding: 15px;
  }
  .hero-content {
    padding: 10px;
    text-align: center;
  }
  .hero-title {
    font-size: 1.8em;
  }
  .hero-subtitle {
    font-size: 0.95em;
  }
  .hero-image {
    min-width: 100%;
  }
  .features-grid, .categories-grid {
    grid-template-columns: 1fr;
  }
  .feature-card, .category-card {
    padding: 10px;
  }
  .category-header {
    padding: 10px;
    flex-direction: column;
    text-align: center;
  }
  .category-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
  .category-info h3 {
    font-size: 1em;
  }
  .category-info p {
    font-size: 0.8em;
  }
  .category-stats {
    padding: 6px 10px;
    font-size: 0.8em;
  }
  .section-title {
    flex-direction: column;
    align-items: flex-start;
  }
  .section-title h2 {
    font-size: 1.3em;
  }
  .posts-list, .announcements {
    padding: 15px;
  }
  .announcement-content h3 {
    font-size: 1.1em;
  }
  .announcement-content p {
    font-size: 0.9em;
  }
}

@media (max-width: 576px) {
  .home {
    padding: 5px;
  }
  .hero-section {
    padding: 10px;
  }
  .hero-content {
    padding: 5px;
  }
  .hero-title {
    font-size: 1.6em;
  }
  .hero-subtitle {
    font-size: 0.9em;
  }
  .feature-card, .category-card {
    padding: 8px;
  }
  .category-header {
    padding: 8px;
  }
  .category-icon {
    width: 30px;
    height: 30px;
  }
  .category-info h3 {
    font-size: 0.95em;
  }
  .category-info p {
    font-size: 0.75em;
  }
  .category-stats {
    padding: 4px 8px;
    font-size: 0.75em;
  }
  .section-title h2 {
    font-size: 1.2em;
  }
  .posts-list, .announcements {
    padding: 10px;
  }
  .announcement-content h3 {
    font-size: 1em;
  }
  .announcement-content p {
    font-size: 0.85em;
  }
}
/* --- --- */
</style>
